<?php

namespace App\Http\Controllers\Api;

use App\Describe;
use App\Subject;
use App\SubjectSort;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class DescribesController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $lists = Describe::orderBy('id', 'asc');
        if ($request->sort) {
            $lists = $lists->where('sort', $request->sort);
        }
        return $lists->with(['sort'])->get();
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        if (!SubjectSort::find($request->subject_sort_id)) {
            return response(['message' => '题目分类不存在'], 400);
        }
        Describe::create($request->all());
        return response(['message' => '添加成功']);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Describe $describe
     * @return \Illuminate\Http\Response
     */
    public function show(Describe $describe)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Describe $describe
     * @return \Illuminate\Http\Response
     */
    public function edit(Describe $describe)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \App\Describe $describe
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Describe $describe)
    {
        $res=$describe->update($request->only(['content']));
        if($res){
            return response(['message' => '修改成功']);
        }
        return response(['message' => '修改失败'],400);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Describe $describe
     * @return \Illuminate\Http\Response
     */
    public function destroy(Describe $describe)
    {
        if (Subject::where('sort', $describe->id)->first()) {
            return response(['message' => '该描述下存在题目，不能删除'], 400);
        }
        $describe->delete();
        return response(['message' => '删除成功']);
    }
}
